import type { LoginParamsData, UserInfoData } from '@/api/userInfo'
import { defineStore } from 'pinia'
import userInfoApi from '@/api/userInfo'
import { staticRoutes,allSyncRoutes,anyRoute } from '@/router/routes'
import type { RouteRecordRaw } from 'vue-router'
import cloneDeep from 'lodash/cloneDeep'
import router from '@/router'
interface storeData{
  token:string,
  userInfo:UserInfoData,
  menuRoutes:RouteRecordRaw[]
}

function filterAllSyncRoutes(allSyncRoutes:RouteRecordRaw[],routesName:string[]){
  let result=allSyncRoutes.filter(item=>{
    if (routesName.indexOf(item.name as string)!==-1) {
      if (item.children) {
        item.children=filterAllSyncRoutes(item.children,routesName)
      }
      return true
    }
  })
  return result 
}

function addRoutes(routes:RouteRecordRaw[]){
  routes.forEach(item=>{
    router.addRoute(item)
  })
}

function routeSet(){
  let result=router.getRoutes()
  result.forEach(item=>{
    router.removeRoute(item.name as string)
  })
  addRoutes(staticRoutes)
}


export const useUserInfoStore = defineStore('userInfo',{
  state():storeData{
    return {
      token:localStorage.getItem('token_key') ||'',
      userInfo:{
        name:'',
        avatar:'',
        routes:[],
        buttons:[],
        roles:[]
      },
      menuRoutes:staticRoutes
    }
  },
   actions:{
    //  登录逻辑
    async login(loginParams:LoginParamsData){
      try {
        const result=await userInfoApi.userLogin(loginParams)
        this.token=result.token
        localStorage.setItem('token_key',result.token)
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取用户信息
    async getInfo(){
      try {
        const result=await userInfoApi.getuserInfo()
        this.userInfo=result
        let newsRoute=filterAllSyncRoutes(cloneDeep(allSyncRoutes),result.routes)
        addRoutes(newsRoute.concat(anyRoute))
        this.menuRoutes=staticRoutes.concat(allSyncRoutes,anyRoute)
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },
    async reset(){
      this.token = ''
      this.userInfo = {
        name:'',
        avatar:'',
        routes:[],
        buttons:[],
        roles:[]
      }
      
      localStorage.removeItem('token_key')
    },
    async logout(){
      try {
        await userInfoApi.logout()
        this.reset()
        routeSet()
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    } 

   },
   getters:{}
})